using System;
using TMPro;
using UnityEngine;
using UnityEngine.Localization;

/// <summary>
/// 将输入作为key自动翻译,todo 不知道table
/// </summary>
public class TextToKeyOnChange : MonoBehaviour
{
    [Serializable]
    class TextFormKey : ITextPreprocessor
    {
        [SerializeField] LocalizedString _localizedString;

        public TextFormKey(LocalizedString localizedString)
        {
            _localizedString = localizedString;
        }

        public string PreprocessText(string text)
        {
            if (string.IsNullOrWhiteSpace(text) || string.IsNullOrEmpty(text) || _localizedString == null)
            {
                return text;
            }

            _localizedString.TableEntryReference = text;
            if (_localizedString.IsEmpty) return text;
            return _localizedString.GetLocalizedString(text);
        }
    }

    [SerializeField] TMP_Text _text;
    [SerializeField] LocalizedString _localizedString;

    void Start()
    {
        if (_text is null) _text = GetComponent<TMP_Text>();
        _text.textPreprocessor = new TextFormKey(_localizedString);
    }
}